<?php
/*
 +----------------------------------------------------------------------
 + Title        : LoginService 控制器
 + Author       : Randy_chen
 + Version      : V1.0.0.1
 + Initial-Time : 2019/8/9 15:57
 + Last-time    : 2019/8/9 15:57+ 86187
 + Desc         : LoginService
 +----------------------------------------------------------------------
*/


namespace app\admin\service;


use app\common\lib\exception\ApiException;
use app\common\service\BaseService;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use think\Db;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Request;

class LoginService extends BaseService
{
    protected $table = 'sys_user';

    /**
     *
     * @param $data
     *
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws ApiException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author : Randy_chen
     * @Date   : 2019/8/9
     * @Time   : 16:27
     */
    public function login(){
        $data = \request()->param();
	    $map = [
		    'is_deleted' => '0',
		    'username'   => $data['username']
	    ];
	    $user = Db::name('SysUser')
	              ->field('id,username,password,authorize,status')
	              ->where($map)
	              ->order('id desc')
	              ->find();
        if (empty($user)) throw new ApiException(10900);
        if (empty($user['status'])) throw new ApiException(10901);
        // 账号锁定消息
        $cache = cache("user_login_{$user['username']}");
        if (is_array($cache) && !empty($cache['number']) && !empty($cache['time'])) {
            if ($cache['number'] >= 10 && ($diff = $cache['time'] + 3600 - time()) > 0) {
                throw new ApiException(10902);
            }
        }
        if (md5($data['password']) !== $user['password']) {
            if (empty($cache) || empty($cache['time']) || empty($cache['number']) || $cache['time'] + 3600 < time()) {
                $cache = ['time' => time(), 'number' => 1, 'geoip' => Request::ip()];
            } elseif ($cache['number'] + 1 <= 10) {
                $cache = ['time' => time(), 'number' => $cache['number'] + 1, 'geoip' =>  Request::ip()];
            }
            cache("user_login_{$user['username']}", $cache);
            if (($diff = 10 - $cache['number']) > 0) {
                throw new ApiException(10903);
            } else {
                sysoplog('系统管理', "账号{$user['username']}连续10次登录密码错误，请注意账号安全！");
                throw new ApiException(10903);
            }
        }
        // 登录成功并更新账号
        cache("user_login_{$user['username']}", null);
	    Db::name('SysUser')
	      ->where(['id' => $user['id']])
	      ->update([
		               'login_at' => Db::raw('now()'),
		               'login_ip' => \request()->ip(),
		               'login_num' => Db::raw('login_num+1'),
	               ]);
        sysoplog('移动端系统管理', '用户登录系统成功');
        $res = $this->applyUserAuth($user['authorize']);
        Cache::set('ADMIN_NODES_'.$user['id'] , $res , 3600*24);
        unset($user['password']);
	    $user['nodes'] = $res;
	    $user['token'] = TokenService::setToken(['user' => $user]);
        return $user;
    }
//"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImp0aSI6IndlY2hhdCJ9.eyJpc3MiOiJ3eC5kaW5nbHUudG9wIiwiYXVkIjoid3guZGluZ2x1LnRvcCIsImp0aSI6IndlY2hhdCIsImlhdCI6MTU2NTU3MzYwNiwiZXhwIjoxNTY1NTczNjA2LCJ1c2VyIjp7ImlkIjoxMDAwMSwidXNlcm5hbWUiOiJ0ZXN0IiwiYXV0aG9yaXplIjoiMSIsInN0YXR1cyI6MSwiYXV0aCI6WyJhZG1pbiIsImFkbWluXC9hdXRoIiwiYWRtaW5cL2F1dGhcL2luZGV4IiwiYWRtaW5cL2F1dGhcL2FwcGx5IiwiYWRtaW5cL2F1dGhcL2FkZCIsImFkbWluXC9hdXRoXC9lZGl0IiwiYWRtaW5cL2F1dGhcL3JlZnJlc2giLCJhZG1pblwvYXV0aFwvZm9yYmlkIiwiYWRtaW5cL2F1dGhcL3Jlc3VtZSIsImFkbWluXC9hdXRoXC9yZW1vdmUiLCJhZG1pblwvY29uZmlnIiwiYWRtaW5cL2NvbmZpZ1wvaW5mbyIsImFkbWluXC9jb25maWdcL3NhdmUiLCJhZG1pblwvbWVudSIsImFkbWluXC9tZW51XC9pbmRleCIsImFkbWluXC9tZW51XC9hZGQiLCJhZG1pblwvbWVudVwvZWRpdCIsImFkbWluXC9tZW51XC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WxlY3QiLCJ3ZWNoYXRcL25ld3NcL2FkZCIsIndlY2hhdFwvbmV3c1wvZWRpdCJdfX0.yuORRfB9WiGDw5T_M8SdtOdyqmOCD1UXXl9vSKdjOZA"
    public function applyUserAuth($authorize){
        if (!empty($authorize) && $authids = explode(',', $authorize)) {
	        $auths = Db::name('SysAuth')
	                   ->where(['status' => '1'])
	                   ->whereIn('id', $authids)
	                   ->column('id');
	        $auth = Db::name('SysAuthNode')
	                  ->whereIn('auth', $auths)
	                  ->column('node');
	        return $auth;
        }
    }


}